var imageResource;
var imageResourceOverlay;
var scaleX = 600;
var scaleY = 338;
var lastEvent;;

function createFaceOverlay(event) {
    var canvas = document.createElement('canvas');
    canvas.setAttribute('width', scaleX);
    canvas.setAttribute('height', scaleY);

    var context = canvas.getContext('2d');
    context.setTransform(1,0,0,1,0,0);
    context.translate(scaleX/2,scaleY/2);

    context.lineWidth = 6;
    context.fillStyle = '#FFF';

    // eyes
    context.strokeStyle = '#f00';

    context.beginPath();
    context.arc(scaleX * event.leftEye.x,
            scaleY * event.leftEye.y, 5, 0, 2*Math.PI);
    context.stroke();

    context.beginPath();
    context.arc(scaleX * event.rightEye.x,
            scaleY * event.rightEye.y, 5, 0, 2*Math.PI);
    context.stroke();


    context.strokeStyle = '#00f';

    // mouth
    context.beginPath();
    context.moveTo(scaleX * event.mouthLeft.x,
            scaleY * event.mouthLeft.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.upperLip.x,
            scaleY * event.upperLip.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.mouthRight.x,
            scaleY * event.mouthRight.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.lowerLip.x,
            scaleY * event.lowerLip.y, 5, 0, 2*Math.PI);
    context.closePath();
    context.stroke();


    context.strokeStyle = '#fff';

    // nose
    context.beginPath();
    context.moveTo(scaleX * event.noseRoot.x,
            scaleY * event.noseRoot.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.noseTip.x,
            scaleY * event.noseTip.y, 5, 0, 2*Math.PI);
    context.stroke();

    context.strokeStyle = '#0f0';

    // left eyebrow
    context.beginPath();
    context.moveTo(scaleX * event.leftEyebrowLeft.x,
            scaleY * event.leftEyebrowLeft.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.leftEyebrowRight.x,
            scaleY * event.leftEyebrowRight.y, 5, 0, 2*Math.PI);
    context.stroke();

    // right eyebrow
    context.beginPath();
    context.moveTo(scaleX * event.rightEyebrowLeft.x,
            scaleY * event.rightEyebrowLeft.y, 5, 0, 2*Math.PI);
    context.lineTo(scaleX * event.rightEyebrowRight.x,
            scaleY * event.rightEyebrowRight.y, 5, 0, 2*Math.PI);
    context.stroke();

    return canvas.toDataURL();

};

function updateOverlay() {
    var newResource = gapi.hangout.av.effects.createImageResource(
            createFaceOverlay(lastEvent));

    var newResourceOverlay = newResource.createOverlay({
            'scale': {
                'magnitude': 1,
                'reference':
                gapi.hangout.av.effects.ScaleReference.WIDTH
            }
    });
    // Put the text x-centered and near the bottom of the frame
    // newResourceOverlay.setPosition(0.5, 0);
    newResourceOverlay.setVisible(true);
    if (imageResource && imageResourceOverlay) {
        imageResourceOverlay.dispose();
        imageResource.dispose();
    }

    imageResource = newResource;
    imageResourceOverlay = newResourceOverlay;
};

function onFaceTrackingChanged(event) {
    try {
        if (event.hasFace) {
            lastEvent = event;
            updateOverlay();
        }
    } catch(e) {
        console.log("onFaceTrackingChanged: ERROR");
        console.log(e);
    }
};

function handleMirrorChange(obj) {
    window.console.log('Checked: ' + obj.target.checked);
    window.console.log(obj);
    gapi.hangout.av.setLocalParticipantVideoMirrored(obj.target.checked);
};

function init(eventObj) {
    if (eventObj.isApiReady) {
        // mirroring
        gapi.hangout.av.setLocalParticipantVideoMirrored(false);
        var mirrorCheckbox = document.getElementById('mirrorVideo');
        mirrorCheckbox.checked =
                gapi.hangout.av.isLocalParticipantVideoMirrored();
        mirrorCheckbox.onchange = handleMirrorChange;

        // Add event handler.
        gapi.hangout.av.effects.onFaceTrackingDataChanged.
                add(onFaceTrackingChanged);

        window.console.log("initialized");
    }
};

function animationLoop() {
    window.setTimeout(animationLoop, 100);
    if (!lastEvent) {
        return;
    }
    updateOverlay();
};

// Wait for gadget to load.
gadgets.util.registerOnLoadHandler(function() {
    gapi.hangout.onApiReady.add(init);
});
